package com.example.stock.service.impl;

import com.example.stock.excel.*;
import com.example.stock.service.WuguService;
import com.example.stock.util.DataUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j2
public class WuguServiceImpl implements WuguService {

    @Override
    public List<Wugu> getWuguList() {
        return DataUtil.getWuguList();
    }

    Map<String, Wugu> wuguMap;

    private Map<String, Wugu> getRawWuguMap() {
        if (wuguMap == null) {
            wuguMap = getWuguList().stream()
                    .collect(Collectors.toMap(Wugu::getStock, wugu -> wugu));
        }
        return wuguMap;
    }

    @Override
    public Wugu getRawWugu(String stock) {
        return getRawWuguMap().get(stock);
    }

    Map<String, WuguHistory> wuguHistoryMap;

    private Map<String, WuguHistory> getWuguHistoriesMap()
    {
        if  (wuguHistoryMap == null) {
            wuguHistoryMap =  getWuguHistories().stream().collect(Collectors.toMap(WuguHistory::getStock, w -> w));
        }
        return wuguHistoryMap;
    }

    private List<WuguHistory> wuguHistories;

    @PostConstruct
    private void init() {
        wuguHistories = DataUtil.getListData(WuguHistory.class, ExcelReaderUtil.FILE_OPERATION,"吾股历史数据");

        // rebuild
        wuguHistories.forEach(w -> {
            Wugu rawWugu = getRawWugu(w.getStock());
            if (rawWugu != null) {
                w.setRankNow(rawWugu.getWugu());
                w.setIndustry(rawWugu.getIndustry());
                w.setIncreased(w.getRank2024() - w.getRankNow());
            }
        });
    }

    @Override
    public List<WuguHistory> getWuguHistories() {
        return wuguHistories;
    }


    @Override
    public WuguHistory getWuguHistory(String stock) {
        return getWuguHistoriesMap().get(stock);
    }
}
